//
//  CZEmoticonKeyboard.swift
//  61.新工程表情键盘
//
//  Created by apple on 16/3/7.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 表情键盘的view
class CZEmoticonKeyboard: UIView {
    
    // MARK: - 属性
    private let ReuseIdentifier = "ReuseIdentifier"
    
    // 布局
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        prepareUI()
    }
    
    /**
     准备UI
     */
    private func prepareUI() {
        // 1.添加子控件
        addSubview(collectionView)
        addSubview(toolBar)
        
        // 2.设置约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // collectionView 水平
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv" : collectionView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb" : toolBar]))
        
        // 垂直
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView, "tb": toolBar]))
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置collectionView cell的大小
        layout.itemSize = collectionView.frame.size
        
    }
    // MARK: - 懒加载
    // collectionView
    private lazy var collectionView: UICollectionView = {
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
        
        // 注册cell
        cv.registerClass(CZEmoticonPageCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        cv.delegate = self
        cv.dataSource = self
        cv.bounces = false
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false

        self.layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        self.layout.minimumLineSpacing = 0


        return cv
    }()
    
    // toolBar
    private lazy var toolBar: CZEmoticonToolBar = {
        let bar = CZEmoticonToolBar.emoticonToolBar()
        bar.delegate = self
        return bar
    }()
}

// MARK: - 扩展CZEmoticonKeyboard 实现 CZEmoticonToolBarDelegate
extension CZEmoticonKeyboard: CZEmoticonToolBarDelegate {
    func toolBarButtonClick(type: CZEmoticonToolBarType) {
        // 滚动到的indexPath
        let indexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
}

// MARK: - 扩展CZEmoticonKeyboard 实现UICollectionViewDataSource和UICollectionViewDelegate
extension CZEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    /// collectionView显示的组数
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 4
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonPageCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.indexPath = indexPath
        
        return cell
    }
    
    // 监听scrollView的滚动.来判断该显示哪个section
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 获取中心点
        var referencePoint = scrollView.center
        referencePoint.x += scrollView.contentOffset.x
        
        // 获取所有正在显示cell的indexPath
        let indexPaths = collectionView.indexPathsForVisibleItems()
        
        // 遍历所有正在显示cell的indexPath
        for indexPath in indexPaths {
            // 通过indexPath获取正在cell
            let cell = collectionView.cellForItemAtIndexPath(indexPath)
            
            // 判断中心点是否在cell的frame里面
            if CGRectContainsPoint(cell!.frame, referencePoint) {
                // 包含,找到了
                
                print("包含,找到了indexPath: \(indexPath.section)")
                
                // 让toolBar对应的按钮选中
                toolBar.switchSelectButtonWitchSelectSection(indexPath.section)
                break
            }
        }
    }
}
